// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import axios from 'axios'

Vue.config.productionTip = false
axios.defaults.withCredentials=true
// 使用ElementUi
Vue.use(ElementUI)

// http request拦截器
axios.interceptors.request.use(
  config => {
    if (localStorage.token) {   // 判断是否存在token，如果存在的话，则每个
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
)

// http response拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      console.log('axios'+error.response.status)
      switch(error.response.status) {
        case 401:
          // 返回401,清除token信息并跳转到登录页面
          store.commit('LOG_OUT');
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
      }
    }
  }
)
// 注册axios为全局变量
Vue.prototype.$axios = axios

// 设置路由防卫
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    if (localStorage.token) {  // 获取当前的token是否存在
      console.log("token存在");
      next();
    } else {
      console.log("token不存在");
      next({
        path: '/login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: {redirect: to.fullPath}
      })
    }
  }
  else { // 如果不需要权限校验，直接进入路由界面
    next();
  }
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
